#!/bin/bash
# 多系统 Docker 安装脚本（国内优化版）
# 支持：Ubuntu/Debian/CentOS/Fedora/Arch Linux
# 功能：自动检测系统 → 检查现有安装 → 安装必要工具 → 配置国内源 → 安装Docker → 安装Docker Compose

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

# 检查 root 权限
check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "${RED}错误：请使用 root 用户或通过 sudo 运行此脚本${NC}"
        exit 1
    fi
}

# 检测 Docker 是否已安装
check_docker_installed() {
    if command -v docker &>/dev/null; then
        echo -e "${GREEN}检测到 Docker 已安装: $(docker --version)${NC}"
        return 0
    else
        return 1
    fi
}

# 检测 Docker Compose 是否已安装
check_compose_installed() {
    if command -v docker-compose &>/dev/null; then
        echo -e "${GREEN}检测到 Docker Compose 已安装: $(docker-compose --version)${NC}"
        return 0
    # 检查新版本 Docker Compose 插件
    elif docker compose version &>/dev/null; then
        echo -e "${GREEN}检测到 Docker Compose 插件已安装: $(docker compose version)${NC}"
        return 0
    else
        return 1
    fi
}

# 检测系统信息
detect_os() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$ID
        OS_LIKE=${ID_LIKE%% *}
        VERSION=$VERSION_ID
    elif type lsb_release >/dev/null 2>&1; then
        OS=$(lsb_release -si | tr '[:upper:]' '[:lower:]')
        VERSION=$(lsb_release -sr)
    elif [ -f /etc/centos-release ]; then
        OS="centos"
        VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/centos-release | cut -d'.' -f1)
    else
        echo -e "${RED}错误：无法检测操作系统类型${NC}"
        exit 1
    fi

    case "$OS" in
        ubuntu|debian|centos|fedora|arch|manjaro)
            echo -e "${GREEN}检测到系统: $OS $VERSION${NC}"
            ;;
        *)
            echo -e "${RED}不支持的操作系统: $OS${NC}"
            exit 1
            ;;
    esac
}

# 安装必要工具
install_required_tools() {
    local missing=()
    
    for tool in curl git; do
        if ! command -v "$tool" &>/dev/null; then
            missing+=("$tool")
        fi
    done
    
    if [ ${#missing[@]} -eq 0 ]; then
        echo -e "${GREEN}必要工具已安装${NC}"
        return
    fi

    echo -e "${YELLOW}正在安装必要工具: ${missing[*]}${NC}"
    
    case "$OS" in
        ubuntu|debian)
            apt-get update >/dev/null
            apt-get install -y "${missing[@]}" >/dev/null
            ;;
        centos|fedora|rhel)
            yum install -y "${missing[@]}" >/dev/null
            ;;
        arch|manjaro)
            pacman -Sy --noconfirm "${missing[@]}" >/dev/null
            ;;
    esac
    
    # 验证安装
    for tool in "${missing[@]}"; do
        if ! command -v "$tool" &>/dev/null; then
            echo -e "${RED}$tool 安装失败，尝试更换源...${NC}"
            change_mirror
            install_with_mirror "${missing[@]}"
            break
        fi
    done
}

# 更换源后安装工具
install_with_mirror() {
    case "$OS" in
        ubuntu|debian)
            apt-get update >/dev/null
            apt-get install -y "$@" >/dev/null
            ;;
        centos|fedora|rhel)
            yum clean all >/dev/null
            yum makecache >/dev/null
            yum install -y "$@" >/dev/null
            ;;
        arch|manjaro)
            pacman -Sy --noconfirm "$@" >/dev/null
            ;;
    esac
    
    # 最终验证
    for tool in "$@"; do
        if ! command -v "$tool" &>/dev/null; then
            echo -e "${RED}$tool 安装失败，请手动安装后重试${NC}"
            exit 1
        fi
    done
}

# 切换国内源
change_mirror() {
    case "$OS" in
        ubuntu|debian)
            echo -e "${YELLOW}正在切换为清华源...${NC}"
            sed -i 's|http://.*archive.ubuntu.com|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list
            sed -i 's|http://security.ubuntu.com|https://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list
            ;;
        centos|fedora|rhel)
            echo -e "${YELLOW}正在切换为阿里云源...${NC}"
            mkdir -p /etc/yum.repos.d/backup
            mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ 2>/dev/null
            curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-${VERSION}.repo || \
            wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-${VERSION}.repo
            ;;
        arch|manjaro)
            echo -e "${YELLOW}正在切换为清华源...${NC}"
            sed -i 's|^Server = .*|Server = https://mirrors.tuna.tsinghua.edu.cn/archlinux/$repo/os/$arch|' /etc/pacman.d/mirrorlist
            ;;
    esac
    
    # 更新源缓存
    case "$OS" in
        ubuntu|debian) apt-get update >/dev/null ;;
        centos|fedora|rhel) yum clean all >/dev/null; yum makecache >/dev/null ;;
        arch|manjaro) pacman -Syy >/dev/null ;;
    esac
}

# 安装 Docker
install_docker() {
    echo -e "${YELLOW}开始安装 Docker...${NC}"
    
    case "$OS" in
        ubuntu|debian)
            apt-get remove -y docker docker-engine docker.io containerd runc >/dev/null
            apt-get install -y \
                apt-transport-https \
                ca-certificates \
                curl \
                gnupg \
                software-properties-common >/dev/null
            
            install -m 0755 -d /etc/apt/keyrings
            curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/$OS/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
            chmod a+r /etc/apt/keyrings/docker.gpg
            
            echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.aliyun.com/docker-ce/linux/$OS $(lsb_release -cs) stable" | \
                tee /etc/apt/sources.list.d/docker.list > /dev/null
            
            apt-get update >/dev/null
            apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin >/dev/null
            ;;
        centos|fedora|rhel)
            yum remove -y docker \
                      docker-client \
                      docker-client-latest \
                      docker-common \
                      docker-latest \
                      docker-latest-logrotate \
                      docker-logrotate \
                      docker-engine >/dev/null
            
            yum install -y yum-utils device-mapper-persistent-data lvm2 >/dev/null
            yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo >/dev/null
            yum install -y docker-ce docker-ce-cli containerd.io >/dev/null
            ;;
        arch|manjaro)
            pacman -Sy --noconfirm docker >/dev/null
            ;;
    esac
    
    systemctl start docker
    systemctl enable docker >/dev/null 2>&1
    
    if docker --version &>/dev/null; then
        echo -e "${GREEN}Docker 安装成功！版本：$(docker --version | awk '{print $3}')${NC}"
    else
        echo -e "${RED}Docker 安装失败！${NC}"
        exit 1
    fi
}

# 安装 Docker Compose
install_compose() {
    echo -e "${YELLOW}开始安装 Docker Compose...${NC}"
    
    # 尝试curl下载
    if command -v curl &>/dev/null; then
        if curl -L https://get.daocloud.io/docker/compose/releases/download/v2.20.3/docker-compose-$(uname -s)-$(uname -m) \
            -o /usr/local/bin/docker-compose >/dev/null 2>&1; then
            chmod +x /usr/local/bin/docker-compose
            ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
            
            if docker-compose --version &>/dev/null; then
                echo -e "${GREEN}Docker Compose 安装成功！版本：$(docker-compose --version | awk '{print $3,$4,$5}')${NC}"
                return
            fi
        fi
    fi

    # 如果curl失败，使用git clone方式
    echo -e "${YELLOW}使用Git备用方案安装...${NC}"
    
    if git clone -q --depth 1 https://gitee.com/banban1000/docker-compose.git /usr/local/bin/compose1 >/dev/null 2>&1; then
        if cp -f /usr/local/bin/compose1/docker-compose /usr/local/bin/ >/dev/null 2>&1; then
            chmod +x /usr/local/bin/docker-compose
            ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
            rm -rf /usr/local/bin/compose1 >/dev/null 2>&1
            
            if docker-compose --version &>/dev/null; then
                echo -e "${GREEN}Docker Compose 安装成功！${NC}"
                return
            fi
        fi
    fi

    echo -e "${RED}Docker Compose 安装失败！${NC}"
    exit 1
}

# 配置用户组
setup_user_group() {
    if [ "$SUDO_USER" != "" ] && [ "$SUDO_USER" != "root" ]; then
        echo -e "${YELLOW}正在将用户 $SUDO_USER 添加到 docker 组...${NC}"
        groupadd docker 2>/dev/null
        usermod -aG docker $SUDO_USER
        echo -e "${GREEN}配置完成！请执行以下命令生效：${NC}"
        echo -e "    ${GREEN}newgrp docker${NC}"
    fi
}

# docker deamon
# bash -c "$(curl -fsSL https://gitee.com/banban1000/docker/raw/master/dsm/rewrite_daemen.sh)"


# 测试 Docker
test_docker() {
    echo -e "${YELLOW}正在运行测试容器...${NC}"
    if docker run --rm hello-world | grep -q "Hello from Docker!"; then
        echo -e "${GREEN}Docker 测试成功！${NC}"
    else
        echo -e "${RED}Docker 测试失败！${NC}"
        exit 1
    fi
}

# 主函数
main() {
    check_root
    
    echo -e "\n${GREEN}=== 检测系统环境 ===${NC}"
    detect_os
    
    # 检查 Docker 是否已安装
    if check_docker_installed; then
        echo -e "${YELLOW}Docker 已经安装，跳过 Docker 安装步骤${NC}"
    else
        echo -e "\n${GREEN}=== 检查系统环境 ===${NC}"
        install_required_tools
        
        echo -e "\n${GREEN}=== 安装 Docker ===${NC}"
        install_docker
    fi
    
    # 检查 Docker Compose 是否已安装
    if check_compose_installed; then
        echo -e "${YELLOW}Docker Compose 已经安装，跳过安装步骤${NC}"
    else
        echo -e "\n${GREEN}=== 安装 Docker Compose ===${NC}"
        install_compose
    fi
    
    echo -e "\n${GREEN}=== 系统配置 ===${NC}"
    setup_user_group
    test_docker
    
    echo -e "\n${GREEN}=== 安装完成 ===${NC}"
    echo -e "Docker 版本: $(docker --version)"
    
    # 显示正确的 Compose 版本信息
    if command -v docker-compose &>/dev/null; then
        echo -e "Docker Compose 版本: $(docker-compose --version)"
    elif docker compose version &>/dev/null; then
        echo -e "Docker Compose 插件版本: $(docker compose version)"
    fi
    
    echo -e "\n${YELLOW}提示：非root用户需要重新登录或执行 'newgrp docker' 使权限生效${NC}"
}

main